<template>
  <div>
    <Header>
      <template v-slot:left>
        <span class="weight-title">
          {{ checkedBookData.edition_name }}-{{ checkedBookData.grade_name }}
        </span>
        <div style="margin-left:200px;font-size:20px;">
          {{ isReview ? "智能复习" : "随堂练习" }}
          <i
            v-if="question.isAnswer && !isReview"
            @click="readCollect"
            :class="[
              starList[nowIndex] ? 'el-icon-star-on' : 'el-icon-star-off',
            ]"
            style="color: rgb(241, 209, 149); cursor: pointer;font-size: 20px;"
          ></i>
        </div>
      </template>
    </Header>
    <div class="quick-test question-practice">
      <div class="flex-space-be question-practice-container w1200">
        <div class="question-left question-container">
          <div class="question-header flex-space-be" v-if="question">
            <div class="left-type">
              {{ question.answerType == 1 ? "单项选择" : "填空题" }}
            </div>
          </div>
          <div class="question-box question-left-container" v-if="question">
            <Question
              :question="question"
              :nowIndex="nowIndex + 1"
              :isAnswer="question.isAnswer"
              :classify="5"
              ref="question"
            ></Question>
          </div>
          <div
            class="btn-box mt20"
            v-if="question"
            v-show="nowIndex == questionList.length - 1"
          >
            <el-button
              class="button button-bg-primary"
              @click="checkStudyQuestion"
              :disabled="question.studentAnswer.length <= 0"
              v-show="!question.isAnswer"
              :loading="submitQuestionLoading"
            >
              提交答案
            </el-button>
            <el-button
              class="button button-bg-primary"
              @click="getStudyQuestion"
              v-show="question.isAnswer"
              :loading="nextQuestionLoading"
            >
              下一题
            </el-button>
          </div>
        </div>
        <div class="question-right">
          <div class="question-right-header">
            <h4>题目序号</h4>
            <p>
              <span class="right">正确</span>
              <span class="wrong">错误</span>
              <span class="checked">选中</span>
            </p>
          </div>
          <div class="question-right-container scrollbar">
            <div class="list-num">
              <div
                class="list-num-item click"
                :class="[
                  question.isAnswer && question.isTrue ? 'right-item' : '',
                  question.isAnswer && !question.isTrue ? 'wrong-item' : '',
                  index == nowIndex ? 'checked-item' : '',
                ]"
                v-for="(question, index) in questionList"
                :key="index"
                @click="changeIndex(index)"
              >
                {{ index + 1 }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import Question from "@/components/Question";
import {
  getPracticeQuestion,
  checkPracticeQuestion,
  getReviewQuestion,
  checkReviewQuestion,
} from "../../../api/question";
import {
  addStudentCollectionQuestion,
  deleteStudentCollectionQuestion,
} from "@/api/individuationRead.js";
export default {
  data() {
    return {
      // defaultStart: false,
      checkedBookData: {},
      unitId: null,
      isReview: false,
      questionList: [],
      starList: [],
      reviewQuestionId: [],
      nowIndex: 0,
      question: null,
      nextQuestionLoading: false,
      submitQuestionLoading: false,
    };
  },
  computed: {},
  methods: {
    readCollect() {
      console.log(this.question, "question");
      let data = {
        question_type: this.question.answerType - 1,
        unit_id: this.unitId,
        book_id: this.checkedBookData.book_id,
        source_type: 3,
        link_id: this.question.questionId,
        source: 3,
        is_individ: 0,
      };
      if (this.starList[this.nowIndex] == true) {
        deleteStudentCollectionQuestion(data)
          .then(() => {
            this.$message({
              message: "已取消收藏",
              type: "warning",
            });
            this.$set(this.starList, this.nowIndex, false);
          })
          .catch(() => {
            console.log("失败");
          });
      } else {
        addStudentCollectionQuestion(data)
          .then((res) => {
            if (res.code == "200") {
              this.$message({
                message: "收藏成功",
                type: "success",
              });
            }
            this.$set(this.starList, this.nowIndex, true);
          })
          .catch(() => {
            console.log("失败");
          });
      }
    },
    goStudyCenter() {
      this.$router.push({
        name: "questionStudyCenter",
      });
    },
    changeIndex(index) {
      this.nowIndex = index;
      this.setQuestion();
    },
    setQuestion() {
      this.question = this.questionList[this.nowIndex];
      this.$nextTick(() => {
        if (this.question.answerType == 2 && !this.question.isAnswer) {
          for (let i = 1; i <= this.question.inputNum; i++) {
            document
              .getElementById(`input-${this.question.questionId}-${i}`)
              .addEventListener("input", (e) => {
                this.inputAnswer(e, i);
              });
          }
        }
      });
    },
    inputAnswer(e, index) {
      this.$set(this.question.studentAnswer, index - 1, e.target.value);
    },
    getPracticeQuestion() {
      let questionId = this.questionList
        .map((item) => {
          return item.questionId;
        })
        .slice(-10);
      let data = new FormData();
      data.append("bookId", this.checkedBookData.book_id);
      data.append("unitId", this.unitId);
      data.append("answeredIds", questionId.length > 0 ? questionId : 0);
      this.nextQuestionLoading = true;
      getPracticeQuestion({ data })
        .then((res) => {
          console.log(res, "reas1515");
          this.nextQuestionLoading = false;
          if (res.code == 200) {
            let question = {
              questionId: res.data.id,
              title: res.data.title,
              initTitle: res.data.title,
              inputNum: 0,
              answerType: res.data.type == 1 ? 1 : 2,
              answerList: res.data.optionList.map((answer) => {
                return {
                  answer_id: answer.id,
                  answer: answer.answer,
                  order_index: answer.order_index,
                };
              }),
              isAnswer: false,
              studentAnswer: [],
              startTime: new Date().getTime(),
            };
            if (question.answerType == 2) {
              let index = 1;
              let newTitle = question.title;
              let questionIndex = 1;
              let flag = true;
              // 原本逻辑
              let pos = newTitle.indexOf("_____");
              while (pos !== -1) {
                flag = false;
                newTitle = newTitle.replace(
                  /_{5}/,
                  ` <input class='question-input' autocomplete="off" id='input-${question.questionId}-${index}' onpaste = "return false";></input> `
                );
                index++;
                pos = newTitle.indexOf("_____");
              }
              if (flag) {
                console.log(11111);
                let posStart = newTitle.indexOf("<u>");
                // let posEnd = newTitle.indexOf("</u>");
                while (posStart !== -1) {
                  newTitle = newTitle.replace(
                    /<u>/,
                    ` <u class="already_fix"><input class='question-input' autocomplete="off" id='input-${question.questionId}-${questionIndex}' onpaste = "return false";></input> `
                  );
                  index++;
                  posStart = newTitle.indexOf("<u>");
                }
              }
              question.title = newTitle;
              question.inputNum = index - 1;
            }
            this.starList.push(false);
            this.questionList.push(question);
            this.nowIndex = this.questionList.length - 1;
            this.setQuestion();
          } else if (res.code == 405) {
            this.$alert("暂无试题", "消息提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.goStudyCenter();
              },
            });
          }
        })
        .catch(() => {
          this.nextQuestionLoading = false;
        });
    },
    getReviewQuestion() {
      let questionId = this.reviewQuestionId.slice(-10);
      let data = new FormData();
      data.append("bookId", this.checkedBookData.book_id);
      if (this.unitId) {
        data.append("unitId", this.unitId);
      }
      data.append("answeredIds", questionId.length > 0 ? questionId : 0);
      this.nextQuestionLoading = true;
      getReviewQuestion({ data })
        .then((res) => {
          this.nextQuestionLoading = false;
          if (res.code == 200) {
            console.log(res.data);
            let question = {
              questionId: res.data.id,
              title: res.data.title,
              initTitle: res.data.title,
              inputNum: 0,
              unitId: res.data.unitId,
              answerType: res.data.type == 1 ? 1 : 2,
              answerList: res.data.optionList.map((answer) => {
                return {
                  answer_id: answer.id,
                  answer: answer.answer,
                  order_index: answer.order_index,
                };
              }),
              isAnswer: false,
              studentAnswer: [],
              startTime: new Date().getTime(),
            };
            if (question.answerType == 2) {
              let index = 1;
              let newTitle = question.title;
              let questionIndex = 1;
              let flag = true;
              let pos = newTitle.indexOf("_____");
              while (pos !== -1) {
                flag = false;
                newTitle = newTitle.replace(
                  /_{5}/,
                  ` <input class='question-input' autocomplete="off" id='input-${question.questionId}-${index}' onpaste = "return false";></input> `
                );
                index++;
                pos = newTitle.indexOf("_____");
              }
              if (flag) {
                let posStart = newTitle.indexOf("<u>");
                // let posEnd = newTitle.indexOf("</u>");
                while (posStart !== -1) {
                  newTitle = newTitle.replace(
                    /<u>/,
                    ` <u class="already_fix"><input class='question-input' autocomplete="off" id='input-${question.questionId}-${questionIndex}' onpaste = "return false";></input> `
                  );
                  index++;
                  posStart = newTitle.indexOf("<u>");
                }
              }
              question.title = newTitle;
              question.inputNum = index - 1;
            }
            this.questionList.push(question);
            this.reviewQuestionId.push(question.questionId);
            this.nowIndex = this.questionList.length - 1;
            this.setQuestion();
          } else if (res.code == 405) {
            if (questionId.length <= 0) {
              this.$alert("暂无试题", "消息提示", {
                confirmButtonText: "确定",
                callback: () => {
                  this.goStudyCenter();
                },
              });
            } else {
              this.reviewQuestionId = [];
              this.getReviewQuestion();
            }
          }
        })
        .catch(() => {
          this.nextQuestionLoading = false;
        });
    },
    submitQuestion() {
      for (let i = 0; i < this.question.inputNum; i++) {
        if (!this.question.studentAnswer[i]) {
          this.question.studentAnswer[i] = "";
        }
      }
      let data = {
        book_id: this.checkedBookData.book_id,
        question_id: this.question.questionId,
        unit_id: this.unitId,
        stu_answer_list: this.question.studentAnswer
          .map((answer, index) => {
            if (this.question.answerType == 1) {
              return {
                answer_id: answer,
              };
            } else {
              let answerData = this.question.answerList.filter((item) => {
                return item.order_index == index + 1;
              });
              return {
                answer_id: answerData[0].answer_id,
                stu_answer: answer.trim(),
                order: index + 1,
              };
            }
          })
          .filter((item) => item),
        optionList: this.question.answerList.map((item) => {
          return {
            answer_id: item.answer_id,
            answer: item.answer,
            order_index: item.order_index,
          };
        }),
      };
      this.submitQuestionLoading = true;
      checkPracticeQuestion({ data })
        .then((res) => {
          this.submitQuestionLoading = false;
          if (res.code == 200) {
            this.question.isTrue = res.data.is_true;
            this.question.parse = res.data.parse;
            this.question.title = this.question.initTitle;
            if (this.question.answerType == 1) {
              this.question.trueAnswer = res.data.option_list
                .filter((item) => {
                  return item.is_true == 1;
                })
                .map((item) => {
                  return {
                    answer_id: item.id,
                    answer: item.answer,
                  };
                });
            } else {
              this.question.trueAnswer = res.data.option_list.map((item) => {
                return {
                  answer_id: item.id,
                  answer: item.answer,
                };
              });
            }
            this.question.isAnswer = true;
            this.$refs.question.showParse = true;
            this.question.verifyAnswer = [];
            if (this.question.answerType == 2) {
              for (let i = 1; i <= this.question.inputNum; i++) {
                let answerDataIndex = res.data.stu_answer_list.findIndex(
                  (item) => {
                    return item.order == i;
                  }
                );
                if (
                  answerDataIndex >= 0 &&
                  res.data.stu_answer_list[answerDataIndex]
                ) {
                  this.question.verifyAnswer.push({
                    answer:
                      res.data.stu_answer_list[answerDataIndex].stu_answer,
                    is_true: res.data.stu_answer_list[answerDataIndex].is_true,
                    order: i,
                  });
                } else {
                  this.question.verifyAnswer.push({
                    answer: "",
                    is_true: 0,
                    order: i,
                  });
                }
              }
            }
            console.log(this.question, "this.question");
            this.$forceUpdate();
            // isTrue: 1,
            // parse:
            //   "【分析】句意：明天是周四。今天是周几？It's Friday.是周五。It's Tuesday.是周二。It's Wednesday.是周三。It's Sunday.是周日。根据常识，周四前是周三，故选It's Wednesday.。",
            // trueAnswer: [
            //   { answer_id: 30378, answer: "It's Wednesday.", is_true: 1 },
            // ],
            // studentAnswer: [30378],
            // verifyAnswer: [{ answer_id: 30379, is_true: 0 }],
            //
          }
        })
        .catch(() => {
          this.submitQuestionLoading = false;
        });
    },
    submitReviewQuestion() {
      for (let i = 0; i < this.question.inputNum; i++) {
        if (!this.question.studentAnswer[i]) {
          this.question.studentAnswer[i] = "";
        }
      }
      let data = {
        book_id: this.checkedBookData.book_id,
        question_id: this.question.questionId,
        unit_id: this.unitId || this.question.unitId,
        stu_answer_list: this.question.studentAnswer
          .map((answer, index) => {
            if (this.question.answerType == 1) {
              return {
                answer_id: answer,
              };
            } else {
              let answerData = this.question.answerList.filter((item) => {
                return item.order_index == index + 1;
              });
              return {
                answer_id: answerData[0].answer_id,
                stu_answer: answer.trim(),
                order: index + 1,
              };
            }
          })
          .filter((item) => item),
        optionList: this.question.answerList.map((item) => {
          return {
            answer_id: item.answer_id,
            answer: item.answer,
            order_index: item.order_index,
          };
        }),
      };
      this.submitQuestionLoading = true;
      checkReviewQuestion({ data })
        .then((res) => {
          this.submitQuestionLoading = false;
          if (res.code == 200) {
            this.question.isTrue = res.data.is_true;
            this.question.parse = res.data.parse;
            this.question.title = this.question.initTitle;
            if (this.question.answerType == 1) {
              this.question.trueAnswer = res.data.option_list
                .filter((item) => {
                  return item.is_true == 1;
                })
                .map((item) => {
                  return {
                    answer_id: item.id,
                    answer: item.answer,
                  };
                });
            } else {
              this.question.trueAnswer = res.data.option_list.map((item) => {
                return {
                  answer_id: item.id,
                  answer: item.answer,
                };
              });
            }
            this.question.isAnswer = true;
            this.$refs.question.showParse = true;
            this.question.verifyAnswer = [];
            if (this.question.answerType == 2) {
              for (let i = 1; i <= this.question.inputNum; i++) {
                let answerDataIndex = res.data.stu_answer_list.findIndex(
                  (item) => {
                    return item.order == i;
                  }
                );
                if (
                  answerDataIndex >= 0 &&
                  res.data.stu_answer_list[answerDataIndex]
                ) {
                  this.question.verifyAnswer.push({
                    answer:
                      res.data.stu_answer_list[answerDataIndex].stu_answer,
                    is_true: res.data.stu_answer_list[answerDataIndex].is_true,
                    order: i,
                  });
                } else {
                  this.question.verifyAnswer.push({
                    answer: "",
                    is_true: 0,
                    order: i,
                  });
                }
              }
            }
            this.$forceUpdate();
            // isTrue: 1,
            // parse:
            //   "【分析】句意：明天是周四。今天是周几？It's Friday.是周五。It's Tuesday.是周二。It's Wednesday.是周三。It's Sunday.是周日。根据常识，周四前是周三，故选It's Wednesday.。",
            // trueAnswer: [
            //   { answer_id: 30378, answer: "It's Wednesday.", is_true: 1 },
            // ],
            // studentAnswer: [30378],
            // verifyAnswer: [{ answer_id: 30379, is_true: 0 }],
            //
          }
        })
        .catch(() => {
          this.submitQuestionLoading = false;
        });
    },
    getStudyQuestion() {
      if (this.isReview) {
        this.getReviewQuestion();
      } else {
        this.getPracticeQuestion();
      }
    },
    checkStudyQuestion() {
      if (this.isReview) {
        this.submitReviewQuestion();
      } else {
        this.submitQuestion();
      }
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.unitId = this.$route.query.unitId;
    this.isReview = !!this.$route.query.isReview;
    this.getStudyQuestion();
  },
  components: {
    Header,
    Question,
  },
};
</script>
